/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sockets.tcp;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

/**
 *
 * @author Yann & Jocelyn
 */
// A class to implement the TCP server's connection thread
public class TCPServerThread extends Thread {

    private Socket socket; // This comunication's socket
    private int id; // The client's id

    // The class' constructor taking two parameters : 
    //- the comunication socket
    //- the client's id.
    public TCPServerThread(Socket socket, int id) {
        this.id = id;
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // Print in console a message for each client connection
            System.out.println("Client number " + id + " ("
                    + socket.getRemoteSocketAddress()
                    + ") established connection...");

            // Get and print the stream in the console
            ObjectInputStream ois =
                    new ObjectInputStream(socket.getInputStream());
            Object o;
            while (true) {
                o = ois.readObject();
                if (!(o instanceof String)) {
                    throw new IOException("Object could not be printed.");
                }
                System.out.println("> Client" + id + " : " + o);
            }
        } catch (Exception e) {
            //e.printStackTrace();
            System.err.println("Communication whith client " + id + " ended.");
        }
    }
}
